import os.path
import time
import csv
import xml.etree.ElementTree as ET
#from wand.image import Image
from home.models import Image as MIImage
from home.models import Article
import traceback
def createFolder(contentType):
    """
    return the path to the uploadedfile directory
    @type contentType: str
    @param contentType: the type of file that will be stored (image or csv)
    @rtype: str
    @return the path to the uploadedfile directory
    """
    basePath = 'uploads/'

    year     = str(time.localtime().tm_year)
    month    = str(time.localtime().tm_mon)
    day      = str(time.localtime().tm_mday)

    if not os.path.exists(basePath + year+'/'):
        os.makedirs(basePath + year + '/')
    basePath += year + '/'

    if not os.path.exists(basePath + month + '/'):
        os.makedirs(basePath + month + '/')
    basePath += month + '/'

    if not os.path.exists(basePath + day + '/'):
        os.makedirs(basePath + day + '/')
    basePath += day + '/'

    if not os.path.exists(basePath + contentType + '/'):
        os.makedirs(basePath + contentType + '/')
    return basePath + contentType + '/'

def save(imageInformation):
    """
    write the data into the database
    @type imageInformation: list
    @param imageInformation: the datas
    """
    fileName                    = imageInformation[0]
    image                       = MIImage(file_name = fileName, 
                                          title     = imageInformation[1], 
                                          legend    = imageInformation[2])
    image.doi_link              = imageInformation[3]
    image.label                 = imageInformation[4]
    image.relevant_articleDOI   = imageInformation[5]
    image.is_tagged             = False
    image.is_tagging            = False
    try:
        MIImage.objects.get(file_name = fileName)
    except:
        print image.file_name
        image.save()

def getImageInformationList(csvReader):
    """
    convert the csvReader to a list
    @type csvReader: csv.reader
    @param csvReader: the csvReader, which contents the csv files contents
    @rtype: list
    @return a list which content the csv file data
    """
    imageInformationList = list()
    for row in csvReader:
        r = list()
        for item in row:
            r.append(item)
        imageInformationList.append(r)
    return imageInformationList

def getMetaInformation(metaFilePath):
    """
    handle the csv file
    @type metaFilePath: str
    @param metaFilePath: the path to the csv file
    @rtype: boolean
    @return is the csv file handled correctly
    """
    metaFile    = open(metaFilePath, 'r')
    csvReader   = csv.reader(metaFile)

    fileNameIndex           = -1
    figureTitleIndex        = -1
    figureLegendIndex       = -1
    figureDoiIndex          = -1
    figureLabelIndex        = -1
    relevantArticleIndex    = -1

    imageInformationList = getImageInformationList(csvReader)
    indexList = imageInformationList[0]
    for i in range(len(indexList)):
        if 'FigFilename' in indexList[i] or 'Fig_Filename' in indexList[i]:
            fileNameIndex = i
        elif 'Fig Title' in indexList[i] or 'Fig_Title' in indexList[i]:
            figureTitleIndex = i
        elif 'FigLegend' in indexList[i] or 'Fig_Caption' in indexList[i]:
            figureLegendIndex = i
        elif 'Article URI' in indexList[i] or 'Article_URI' in indexList[i]:
            figureDoiIndex = i
        elif 'FigLabel' in indexList[i] or 'Fig_Label' in indexList[i]:
            figureLabelIndex = i
        elif 'Article DOI' in indexList[i] or 'Article_DOI' in indexList[i]:
            relevantArticleIndex = i

    for i in range(1, len(imageInformationList)):
        imageInformation = list()
        try:
            imageInformation.append(imageInformationList[i][fileNameIndex])
            imageInformation.append(imageInformationList[i][figureTitleIndex])
            imageInformation.append(imageInformationList[i][figureLegendIndex])
            imageInformation.append(imageInformationList[i][figureDoiIndex])
            imageInformation.append(imageInformationList[i][figureLabelIndex])
            imageInformation.append(imageInformationList[i][relevantArticleIndex])
            
            save(imageInformation)
        except:
            return False
    return True
    
def saveArticleInfo(articleFilePath):
    """
    handle the article xml file
    @type articleFilePath: str
    @param articleFilePath: the path to the csv file
    @rtype: boolean
    @return is the xml file handled correctly
    """
    articleFile = open(articleFilePath)
    articleDoc = ET.parse(articleFile)
    print 1
    articleIdNode = articleDoc.find('//front/article-meta/article-id')
    print 2
    articleId = articleIdNode.text
    relevantImages = MIImage.objects.filter(relevant_articleDOI=articleId)
    if len(relevantImages) == 0:
        return False
    newArticle = Article(article_file_location=articleFilePath)
    print newArticle
    for relevantImage in relevantImages:
        relevantImage.article_id = newArticle.id
        try:
            newArticle.save()
            relevantImage.save()
        except:
            return False
    return True

def getArticleInformation(filename):
    
    
    
    return True
'''
def uploadArticles(files):
    
    result = dict()
    
    if '.pdf' in str(files[0].name):
        basePath = createFolder('pdf')
        isMetaUploaded  = True
        with open(basePath + str(files[0].name), 'w+') as destination:
            for chunk in files[0].chunks():
                try:
                    destination.write(chunk)
                except:
                    isMetaUploaded = False
        image = Image.options.get(file_name = the_fileName)
        article = Article.objects.get_or_create(doi = the_doi,article_file_location = basePath + str(files[0].name))
        isSuccessful    = getArticleInformation(basePath + str(files[0].name))

        result['isSuccessful']   = isSuccessful
        result['isMetaUploaded'] = isMetaUploaded
        
    return result
'''
def uploadFiles(files):
    """
    handle the http post image file
    @type files: request.FILES
    @param files: the http post file
    @rtype: the json for the UI
    @return the json file for the UI process
    """
    result = dict()
    if '.csv' in str(files[0].name):
        basePath       = createFolder('csv')
        isMetaUploaded  = True
        
        with open(basePath + str(files[0].name), 'w+') as destination:
            for chunk in files[0].chunks():
                try:
                    destination.write(chunk)
                except:
                    isMetaUploaded = False
        isSuccessful    = getMetaInformation(basePath + str(files[0].name))

        result['isSuccessful']   = isSuccessful
        result['isMetaUploaded'] = isMetaUploaded
    elif 'image/' in str(files[0].content_type) :
        basePath       = createFolder('image')
        #begin uploading image
        isImageUploaded = True

        for imageFile in files:
            with open(basePath + imageFile.name, 'wb+') as destination :
                for chunk in imageFile.chunks():
                    try:
                        destination.write(chunk)
                    except:
                        traceback.print_exc()
                        isImageUploaded = False
            try:
                imageObject     = MIImage.objects.get(file_name=imageFile.name)
                imageFilePath   = basePath + imageFile.name
                imageObject.image_file_location = convertFormat(imageFilePath)
                imageObject.save()
            except:
                traceback.print_exc()
                pass

        result['isSuccessful']      = isImageUploaded
        result['isImageUploaded']   = isImageUploaded
    return result

def convertFormat(imageFilePath):
    fileName, suffix    = os.path.splitext(imageFilePath)
    targetFilePath      = '%s.jpg' %(fileName)
    
    #image               = Image(filename = imageFilePath)
    #image.format        = 'jpg'
    #image.save(filename = targetFilePath)

    return targetFilePath

def uploadArticles(files):
    """
    handle the http post article files
    @type files: request.FILES
    @param files: the http post file
    @rtype: the json for the UI
    @return the json file for the UI process
    """
    result = dict()
    print files
    result['isXMLUploaded'] = False
    result['isSuccessful'] = False
    if '.xml' in str(files.name):
        basePath = createFolder('articles')
        isXMLUploaded = True
        with open(basePath + str(files.name), 'w+') as destination:
            for chunk in files.chunks():
                try:
                    destination.write(chunk)
                except:
                    isXMLUploaded = False
        isSuccessful = saveArticleInfo(basePath + str(files.name))
        result['isXMLUploaded'] = isXMLUploaded
        result['isSuccessful'] = isSuccessful
    return result

